package com.atguigu.eduservice.service.impl;

import com.atguigu.eduservice.entity.EduChapter;
import com.atguigu.eduservice.entity.EduVideo;
import com.atguigu.eduservice.entity.chapter.ChapterVo;
import com.atguigu.eduservice.entity.chapter.VideoVo;
import com.atguigu.eduservice.mapper.EduChapterMapper;
import com.atguigu.eduservice.service.EduChapterService;
import com.atguigu.eduservice.service.EduVideoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author ZhanK
 * @since 2022-02-20
 */
@Service
public class EduChapterServiceImpl extends ServiceImpl<EduChapterMapper, EduChapter> implements EduChapterService {
    @Autowired
    EduVideoService eduVideoService;

    @Override
    public List<ChapterVo> getChapterVoByCourseId(String courseId) {
        //根据传入的课程ID，查出章节列表里面对应的章节
        QueryWrapper<EduChapter> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("course_id", courseId);
        List<EduChapter> eduChapters = baseMapper.selectList(wrapper1);

        //根据传入的课程ID，查出x小节列表里面对应的小节
        QueryWrapper<EduVideo> wrapper2 = new QueryWrapper<>();
        wrapper2.eq("course_id", courseId);
        List<EduVideo> eduVideos = eduVideoService.list(wrapper2);
        //定义一个最终返回ChapterVo的集合添加最后赋值好外边for循环的ChapterVo
        List<ChapterVo> finalChapterVoList = new ArrayList<>();
        //先遍历一级章节，把查出的EduChapter 赋值给要返回界面的ChapterVo，然后在里面在加for循环遍历VideoVo。
        // 如果小节的所属章节id属于当前的章节id就把该遍历的小节加到一个集合里，
        // 然后在外层章节for循环里面把小节集合加到章节的属性Children里面，在同一返回章节的ChapterVo集合给前端
        for (int i = 0; i < eduChapters.size(); i++) {
            EduChapter eduChapter = eduChapters.get(i);
            ChapterVo chapterVo = new ChapterVo();
            BeanUtils.copyProperties(eduChapter, chapterVo);

            ArrayList<VideoVo> videoVos = new ArrayList<>();
            for (int j = 0; j < eduVideos.size(); j++) {
                VideoVo videoVo = new VideoVo();
                BeanUtils.copyProperties(eduVideos.get(j), videoVo); //这里面遍历的是j不是i。。别写错了
                if (eduVideos.get(j).getChapterId().equals(eduChapter.getId())) {
                    videoVos.add(videoVo);
                }

            }

            chapterVo.setChildren(videoVos);
            finalChapterVoList.add(chapterVo);
        }


        return finalChapterVoList;
    }
}
